package com.zlsy.thread.lock.reentrantlock;

import lombok.extern.slf4j.Slf4j;

import java.util.Random;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zhouliang
 * @date 2020/7/29 20:07
 * ReentrantLock演示多线程预定电影院的座位
 */
@Slf4j
public class CinemaBookSeat implements Runnable {
    private static ReentrantLock reentrantLock = new ReentrantLock();

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            CinemaBookSeat r = new CinemaBookSeat();
            Thread thread = new Thread(r, "线程" + i);
            thread.start();
        }
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "：尝试预定电影座位");
        reentrantLock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "：开始预定电影座位");
            try {
                Thread.sleep(new Random().nextInt(1000));
            } catch (InterruptedException e) {
                log.error("", e);
            }
            System.err.println(Thread.currentThread().getName() + "：完成预定电影座位");
        } finally {
            reentrantLock.unlock();
        }
    }
}
